<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type='primary' @click='isShowDialog'>添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table :data='rolesList' border stripe>
        <!-- 展开列 -->
        <el-table-column type='expand'>
          <template slot-scope="scope">
            <el-row :class="['vcenter','btbottom', i1===0? 'bdtop':'']" v-for="(item,i1) in scope.row.children" :key="item.id">
              <el-col :span="5">
                <el-tag>{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 渲染二级权限 -->
                <el-row :class="['vcenter',i2===0? '':'bdtop']" v-for='(item1,i2) in item.children' :key='item1.id'>
                  <el-col :span='6'>
                    <el-tag type='success'>{{ item1.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span='18'>
                    <el-tag closable type='warning' v-for="item2 in item1.children" :key='item2.id' @close='removeRightById(scope.row.id,item2.id)'>{{ item2.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type='index'></el-table-column>
        <el-table-column label="角色名称" prop='roleName'></el-table-column>
        <el-table-column label="角色描述" prop='roleDesc'></el-table-column>
        <el-table-column label="操作">
          <template slot-scope='scope'>
            <!-- 编辑 -->
            <el-button type="primary" icon="el-icon-edit" size='mini' @click='editRoleDialog(scope.row.id)'>编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size='mini' @click='removeRoleById(scope.row.id)'>删除</el-button>
            <!-- 分配权限按钮 -->
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
                <el-button type="warning" icon="el-icon-setting" size='mini' @click='showSetDialog(scope.row)'>分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框模态框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleVisiable" width="50%">
        <!-- 内容主体区域 -->
        <el-form ref='addRoleRef' :model="addForm" :rules="addFormRules" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogvisiable = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setdialogVisible" width="50%" @close='setRightDialogClosed'>
      <!-- 树形控件 -->
      <el-tree show-checkbox :data="rightsList" :props="defaultProps"  ref='treeRef' node-key='id' default-expand-all :default-checked-keys='defKeys'></el-tree>
      <span slot="footer" class="dialog-footer">
       <el-button @click="setdialogVisible = false">取 消</el-button>
       <el-button type="primary" @click="alloRights">确 定</el-button>
     </span>
    </el-dialog>
    <!-- 修改角色信息对话框 -->
    <el-dialog title="修改角色"  :visible.sync="editDvisiable"  width="50%">
        <el-form ref='editFormRef' :model="editForm" :rules='editFormRules' label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDvisiable = false">取 消</el-button>
          <el-button type="primary" @click="editRoleInfo()">确 定</el-button>
        </span>
      </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 所有角色列表数据
      rolesList: [],
      // 分配权限对话框的显示隐藏
      setdialogVisible: false,
      // 获取的权限列表数据
      rightsList: [],
      // 树形控件的绑定对象
      defaultProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id值数组
      defKeys: [],
      // 添加角色对话框的显示隐藏
      addRoleVisiable: false,
      // 添加角色表单
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 当前即将被分配权限的角色id
      roleId: '',
      // 添加角色表单的校验规则
      // 添加用户表单的验证规则
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '用户名长度为3到10之间', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入用户描述信息', trigger: 'blur' }
        ]
      },
      // 修改用户功能对话框的显示隐藏
      editDvisiable: false,
      // 查询到的用户信息对象
      editForm: {},
      // 修改信息表单验证规则对象
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = res.data
    },
    // 展示分配权限数据列表
    async showSetDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      // 存储获取的权限列表
      this.rightsList = res.data
      // 显示对话框
      // 递归获取三级权限的id
      this.getLeafKeys(role, this.defKeys)
      this.setdialogVisible = !this.setdialogVisible
    },
    // 关闭分配权限对话框,清楚defkey的数组,防止影响其余的权限列表的默认展示
    setRightDialogClosed () {
      this.defKeys = []
    },
    // 点击分配权限
    async alloRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log(keys)
      const str = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: str })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      this.$message.success('分配权限成功')
      this.setdialogVisible = !this.setdialogVisible
      this.getRolesList()
    },
    // 根据id删除对应权限
    async removeRightById (id1, id2) {
      const resConfirm = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (resConfirm === 'confirm') {
        const { data: res } = await this.$http.delete(`roles/${id1}/rights/${id2}`)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
      } else {
        this.$message.info('取消删除操作')
      }
      this.getRolesList()
    },
    // 通过递归的方式获取三级权限的id
    getLeafKeys (node, arr) {
      // 不包含children 就是三级
      if (!node.children) {
        console.log(node)
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 控制添加用户角色框的显示隐藏
    isShowDialog () {
      this.addRoleVisiable = !this.addRoleVisiable
    },
    // 添加角色功能
    async addRole () {
      // 预校验功能
      this.$refs.addRoleRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        this.$message.success('添加用户成功')
        this.addRoleVisiable = !this.addRoleVisiable
        // 重新刷新角色列表
        this.getRolesList()
      })
    },
    // 展示编辑角色的对话框
    async editRoleDialog (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取信息失败')
      this.editForm = res.data
      this.editDvisiable = !this.editDvisiable
    },
    // 修改角色信息
    editRoleInfo () {
      // 预校验
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('信息验证失败')
        const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc })
        if (res.meta.status !== 200) return this.$message.error('修改信息失败')
        this.$message.success('修改信息成功')
        this.editDvisiable = !this.editDvisiable
        this.getRolesList()
      })
    },
    // 删除角色
    async removeRoleById (id) {
      const resConfirms = await this.$confirm('此操作将永久删除该角色,是否继续?', '提示', {
        confirmButtonText: '就要删',
        cancelButtonText: '再想下',
        type: 'warning'
      }).catch(err => err)
      if (resConfirms === 'confirm') {
        const { data: res } = await this.$http.delete('roles/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getRolesList()
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .el-tag{
    margin: 7px;
  }
  .bdtop{
    border-top: 1px solid #eee;
  }
  .btbottom{
    border-bottom: 1px solid #eee;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }
  .el-message-box{
    height: 300px;
  }
</style>
